package com.example.material.controller;

import com.example.material.entity.Material;
import com.example.material.service.MaterialService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;

/**
 * 物料管理接口
 */
@RestController
@RequestMapping("/api/materials")
@RequiredArgsConstructor
public class MaterialController {
    private final MaterialService materialService;

    /** 新增物料 */
    @PostMapping
    public Material create(@RequestBody Material material) {
        return materialService.create(material);
    }

    /** 修改物料 */
    @PutMapping("/{id}")
    public Material update(@PathVariable Long id, @RequestBody Material material) {
        return materialService.update(id, material);
    }

    /** 删除物料 */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        materialService.delete(id);
    }

    /** 查询单个物料 */
    @GetMapping("/{id}")
    public Material getById(@PathVariable Long id) {
        return materialService.getById(id);
    }

    /** 查询所有物料 */
    @GetMapping
    public List<Material> getAll() {
        return materialService.getAll();
    }

    /** 导入物料（Excel） */
    @PostMapping("/import")
    public void importExcel(@RequestParam("file") MultipartFile file) {
        materialService.importFromExcel(file);
    }

    /** 导出物料（Excel） */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportExcel() {
        byte[] data = materialService.exportToExcel();
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=materials.xlsx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(data);
    }
} 